/**
 * Copyright (C) © 2014 
 */
package com.whos.swiperefreshandload.view;

import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * @author Ge Liang
 * @Create at 2015-4-29 下午3:48:02
 * @Version 1.0
 *          <p>
 *          <strong>监听view scroll的滑动状态</strong>
 *          </p>
 */
public abstract class OnTouchScrollListener implements OnTouchListener {
    private int lastY        = 0;
    private int touchEventId = -9983761;
    /**
     * The view is not scrolling. Note navigating the list using the trackball counts as
     * being in the idle state since these transitions are not animated.
     */
    public static int SCROLL_STATE_STOP = 0;

    /**
     * The user is scrolling using touch, and their finger is still on the screen
     */
    public static int SCROLL_STATE_TOUCH_SCROLL = 1;

    /**
     * The user had previously been scrolling using touch and had performed a fling. The
     * animation is now coasting to a stop
     */
    public static int SCROLL_STATE_FLING = 2;
    Handler     handler      = new Handler() {
                                 @Override
                                 public void handleMessage(Message msg) {
                                     super.handleMessage(msg);
                                     View scroller = (View) msg.obj;

                                     if (msg.what == touchEventId) {
                                         if (lastY == scroller.getScrollY()) {
                                             // scroll停止了，此处你的操作业务
                                             onScrollStateChanged(lastY, SCROLL_STATE_STOP);
                                         } else {
                                             handler.sendMessageDelayed(handler.obtainMessage(touchEventId, scroller),
                                                 1);
                                             lastY = scroller.getScrollY();
                                             onScrollStateChanged(lastY, SCROLL_STATE_TOUCH_SCROLL);
                                         }
                                     }
                                 }
                             };
    public abstract void onScrollStateChanged(int lastY, int scrollState);
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int eventAction = event.getAction();
        switch (eventAction) {
            case MotionEvent.ACTION_UP:
                // 5ms后观察scroller
                handler.sendMessageDelayed(handler.obtainMessage(touchEventId, v), 5);

            break;
            default:
            break;
        }
        return false;
    }

}
